<script setup>
import { ref,onMounted, nextTick,computed } from 'vue'
import Drawer from '@/components/Drawer.vue'
import AssetsList from '@/components/AssetsList.vue'

import {ElTable, ElTableColumn, ElMessage, ElButton} from 'element-plus'
import { 
  deptList,
  getLocationTree,
  getFixPersonList,
  getFixDept,
  getFixList,
  addFix,
  getFixDetail
} from "@/api/AssetFix.js"

import {Search, Refresh, Plus, View} from '@element-plus/icons-vue'


// 资产列表搜索框绑定的资产名称
const queryForm = ref({
  id: ''
})
// 根据资产名称查询维修列表
const handleFixSearch = () => {
  if (!queryForm.value.id) {
    ElMessage.warning('请输入维修编号');
    return;
  }
  const params = {
    id: queryForm.value.id
  }
  getFixList(params).then(res => {
    if (res.code === 200) {
      fixList.value = res.data
    }
  })
}

// 重置资源维修列表数据
const handleFixReset = () => {
  queryForm.value.id = ''
  getFixListData()
}

// 获取资源维修列表数据
const getFixListData = () => {
  getFixList().then(res => {
    if (res.code === 200) {
      fixList.value = res.data
    }
  })
}
// 弹框状态
const formVisible = ref(false)
const title = ref('')
// 资产借用表单实例对象
const formRef = ref(null)

// 维修表单数据
const fixForm = ref({
  repairApply: null,
  deptId: null,
  locationId: null,
  faultDesc: "",
  startTime: new Date().toISOString().split('T')[0], // 维修日期，默认今天
})

// 位置树形数据
const parentLocations = ref([])


// 维修列表
const fixList = ref([])


// 表单验证规则
const queryRules = {
  locationName: [
    { required: true, message: '请输入位置名称', trigger: 'blur' }
  ]
}

const locationList = ref([])


const fixDept = ref();
const getAssetDeptList = () => {
  deptList().then(res => {
    if (res.code === 200) {
      console.log(res.data, 7877)
      locationList.value = res.data
    }
  })
}

// 借用人相关状态
const fixPersonLoading = ref(false)
const fixPersonOptions = ref([])

// 搜索报修人
const searchFixPerson = async (query) => {
  if (query) {
    fixPersonLoading.value = true
    try {
      const res = await getFixPersonList({ username: query })
      if (res.code === 200) {
        fixPersonOptions.value = res.data
      }
    } finally {
      fixPersonLoading.value = false
    }
  } else {
    fixPersonOptions.value = []
  }
}

// 处理报修人选择变化
const handleFixChange = async (personId) => {
  if (!personId) return;
  
  // 获取报修人详情
  const res = await getFixDept(personId);
  if (res.code === 200) {
    // 自动填充部门信息
    fixDept.value = res.data.departments;
  }
}

// 提交资产借用表单
const handleSubmit = () => {
  // 添加表单校验
  console.log(fixForm.value, 789)
  if(fixForm.value.assets.length<=0) return ElMessage.error('请选择资产')
  formRef.value.validate(async (valid) => {
    if (valid) {
      addFix(fixForm.value).then(res => {
        if (res.code === 200) {
          ElMessage.success(`新增成功`);
          formVisible.value = false;
          // 调用子组件的取消选中方法
          assetsListRef.value?.clearSelection()
          resetForm();
          getFixListData()
        }
      });
    }
  })
}


// 重置表单
const resetForm = () => {

  fixForm.value = { locationName: '', parentId: null };
}

// 新增资产维修
const addFixData = () => {
  formVisible.value = true
  title.value = '新增维修'
}

// 获取位置树形结构
const getLocationTreeData = () => {
  getLocationTree().then(res => {
    if (res.code === 200) {
      parentLocations.value = res.data
    }
  })
}
// 定义子组件 ref
const assetsListRef = ref(null)

// 点击取消关闭弹框
const handleCancel = () => {
  formVisible.value = false
  // 调用子组件的取消选中方法
  assetsListRef.value?.clearSelection()
}

// 获取选择维修的资产
const handleAssetSelect = (assetList) =>{
  fixForm.value.assets = assetList
  console.log(assetList,9999)
}

// 控制 Drawer 显示状态
const drawerVisible = ref(false)
// 关闭 Drawer 的方法
const closeDrawer = () => {
  drawerVisible.value = false
}

const showFormData = ref({
  id: '',
  createTime: "",
  username: '',
  deptName: '',
  locationName: '',
  faultDesc: '',
  assets:[]
})

const formDataValues = computed( () => [
  {
    label: '报修人部门:',
    value: showFormData.value.deptName
  },
  {
    label: '报修人:',
    value: showFormData.value.username
  },

  {
    label: '送检地点:',
    value: showFormData.value.locationName
  },
  {
    label: '备注:',
    value: showFormData.value.faultDesc
  },
  {
    label: '创建时间:',
    value: showFormData.value.createTime
  },
])

// tableData
const tableColumns = ref([
  { prop: 'name', label: '资产名称' },  
  { prop: 'categoryName', label: '资产分类' },
  { prop: 'assetCode', label: '资产编码' },
  { prop: 'model', label: '型号规格' },
  // { prop: 'serialNumber', label: '序列号' },
  { prop: 'locationName', label: '位置' }
])

const tableData = ref([])

// 点击编号时触发的方法
const handleClickTag = (id) => {
  // 给Drawer传递数据 打开 Drawer
  // 思路：点击编号时候，调用接口获取详情接口然后根据返回的数据组合成showFormData格式的数据
  getFixDetail({id}).then(res => {
    if (res.code === 200) {
      console.log(res,"详情数据")
      nextTick(() => {
        showFormData.value.id = res.data.id
        showFormData.value.createTime = res.data.createTime
        showFormData.value.username = res.data.username
        showFormData.value.deptName = res.data.deptName
        showFormData.value.expectedReturn = res.data.expectedReturn
        showFormData.value.locationName = res.data.locationName
        showFormData.value.faultDesc = res.data.faultDesc
        tableData.value = res.data.assets
        console.log(formDataValues.value,7777)
      })
    }
  })
  drawerVisible.value = true
}


onMounted(() => {
  getLocationTreeData()
  getAssetDeptList()
  getFixListData()
})
</script>

<template>
  <!-- 新增资产维修按钮与搜索维修资源列表 -->

    <!-- 搜索框 -->
  <el-form :inline="true" :model="queryForm" style="margin: 10px 0 0 0;">

  <el-form-item>
          <el-space>
            <el-input v-model="queryForm.id" placeholder="请输入维修编号" clearable style="width: 300px"
                      :prefix-icon="Search">
              <template #append>
                <el-button type="primary" :icon="Search" style="background: #409eff;color: #ffffff;"
                           @click="handleFixSearch">搜索
                </el-button>
              </template>
            </el-input>
            <el-button type="primary" plain :icon="Refresh" @click="handleFixReset">重置</el-button>
            <el-button plain type="primary" :icon="Plus" @click="addFixData">新增</el-button>
          </el-space>
        </el-form-item>
  </el-form>



  <el-dialog v-model="formVisible" @close="handleCancel" close-on-click-modal="false" :title="title" width="70%">
    <el-form :model="fixForm" :rules="rules" inline ref="formRef" label-width="120px">
      
      <el-form-item label="报修人" prop="repairApply">
        <el-select
          v-model="fixForm.repairApply"
          filterable
          remote
          clearable
          reserve-keyword
          placeholder="请输入报修人姓名"
          :remote-method="searchFixPerson"
          :loading="fixPersonLoading"
          @change="handleFixChange"
        >
          <el-option
            v-for="item in fixPersonOptions"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="报修人部门" prop="deptId" :rules="[{required:true,message:'请选择资产部门'}]">
        <el-tree-select
            v-model="fixForm.deptId" placeholder="请选择报修人部门"
            :data="fixDept"
            node-key="id"
            clearable
            :props="{label:'deptName',children:'children'}"
            check-strictly
            :render-after-expand="false"
            style="width: 200px"
        ></el-tree-select>
      </el-form-item>

      <el-form-item label="送修地点" prop="locationId">
        <el-tree-select
          v-model="fixForm.locationId" placeholder="请选择送修地点"
          :data="parentLocations"
          node-key="id"
          clearable
          :props="{label:'locationName',children:'children'}"
          check-strictly
          :render-after-expand="false"
          style="width: 200px"
      ></el-tree-select>

      </el-form-item>

      <el-form-item label="报修日期" prop="startTime">
        <el-date-picker
          v-model="fixForm.startTime"
          type="date"
          clearable
          placeholder="选择报修日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="备注" class="full-width">
        <el-input 
          v-model="fixForm.faultDesc" 
          type="textarea" 
          :rows="3" 
          placeholder="请输入备注内容" 
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      

      <!-- 资产列表 -->
      <AssetsList :status="0" ref="assetsListRef" @assetSelect="handleAssetSelect"/>

      <!-- 维修表单内容 -->
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-table 
    :data="fixList"
    table-layout="auto"
    height="80%"
    style="margin-top: 10px;cursor:pointer;"
    >
    <!--    <el-table-column prop="id" label="维修编号" align="left" width="150"/>-->
    <el-table-column prop="dept_name" label="报修人部门" align="left"/>
    <el-table-column prop="username" label="报修人" align="center"/>
    <el-table-column prop="location_name" label="送检地点" align="center"/>
    <el-table-column prop="fault_desc" label="维修事项" align="center">
      <template #default="scope">
        <el-tooltip :content="scope.row.fault_desc" placement="top" :disabled="!scope.row.fault_desc || scope.row.fault_desc.length <= 10">
          <span class="table-cell-truncate">{{ scope.row.fault_desc }}</span>
        </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="报修日期" align="center"/>
    <el-table-column prop="id" label="操作" align="center" width="150">
      <template #default="scope">
        <el-link type="primary" :icon="View" @click="handleClickTag(scope.row.id)">查看</el-link>
      </template>
    </el-table-column>
  </el-table>

  <!--------------- 借用详情抽屉 ----------------->
  <Drawer v-model:visible="drawerVisible" :formData="showFormData" :formDataValues="formDataValues"
          :tableColumns="tableColumns" tableType="fix" :tableData="tableData" @close="closeDrawer"/>
</template>

<style scoped lang='less'>
.mb-4 {
  margin-bottom: 1rem;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
.full-width {
  width: 100%;
  
  .el-textarea {
    width: 100%;
  }
}
.table-cell-truncate {
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px; /* 根据实际情况调整 */
}
</style>